package com.sun.juc.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 第一步 创建资源类，定义属性和操作方法
 * 第二步 调用资源类的操作方法
 */
public class SaleTicket {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        Thread t1 = new Thread(()->{for (int i = 0; i < 30; i++) {ticket.sale();} },"A");
        Thread t2 = new Thread(()->{ for (int i = 0; i < 30; i++) { ticket.sale(); }},"B");
        Thread t3 = new Thread(()->{ for (int i = 0; i < 30; i++) { ticket.sale(); }},"C");
        t1.start();
        t2.start();
        t3.start();
    }
}

class Ticket{
    //票的数量
    private int number = 30;
    private final Lock lock = new ReentrantLock(true);
    public  void sale(){
        lock.lock();
        try{
            if (number > 0) {
                number--;
                System.out.println(Thread.currentThread().getName() + "卖出一张票,剩余" + number + "张票");

            }
        }finally {
            lock.unlock();
//            try {
//                Thread.sleep(100);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
        }


    }
}